import { error, warn } from './utils/output'
import url from './utils/url'

import { checkUserinfo } from './services/userinfoUnit'
import login from './services/login'
import getCampusInfo from './services/getCampusInfo'
import submitRequest from './services/submitRequest'
import getPageResult from './services/getPageResult'
import createServer from './services/createServer'
import UserinfoModel from './model/userinfo.model'
import quit from './utils/quit'

const { loginUrl, UserinfoUrl, signInUrl, generalSignInUrl, pageUrl } = url

const createTask = async (regularSignIn: boolean, userinfo: UserinfoModel): Promise<Array<string>> => {
  const { username } = userinfo
  const headers = await login(loginUrl, userinfo)
  const { id, name, gradeClass } = await getCampusInfo(UserinfoUrl, headers)
  const res = await submitRequest(regularSignIn, userinfo, id!, headers, signInUrl, generalSignInUrl)
  await getPageResult(pageUrl, id!, headers, { name, gradeClass, username }).catch(e => warn(e))
  return [gradeClass, name, res]
}

const main = async (): Promise<Array<PromiseSettledResult<Array<string>>>> => {
  const taskList: Array<Promise<Array<string>>> = []
  const [regularSignIn, userinfoList] = await checkUserinfo()
  for (const userinfo of userinfoList) {
    taskList.push(createTask(regularSignIn, userinfo))
  }
  const res = await Promise.allSettled(taskList)
  const atLeastOneSuccess = res.some(item => item.status === 'fulfilled')
  atLeastOneSuccess && await createServer().catch(e => warn(e))
  return res
}

main()
  .then(res => console.table(res))
  .catch(e => {
    error('操作失败了，原因是', e)
    quit()
  })
